// Static server + DeepSeek proxy API
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');

const PORT = process.env.PORT ? Number(process.env.PORT) : 5173;
const ROOT = __dirname;
const API_KEY = process.env.DEEPSEEK_API_KEY || '';

const TYPES = {
  '.html': 'text/html; charset=utf-8',
  '.css': 'text/css; charset=utf-8',
  '.js': 'application/javascript; charset=utf-8',
  '.json': 'application/json; charset=utf-8',
  '.svg': 'image/svg+xml',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.ico': 'image/x-icon',
  '.txt': 'text/plain; charset=utf-8'
};

function safeResolve(p) {
  const resolved = path.join(ROOT, p);
  const rel = path.relative(ROOT, resolved);
  if (rel.startsWith('..') || path.isAbsolute(rel)) return ROOT; // prevent path traversal
  return resolved;
}

function sendJson(res, status, data) {
  res.statusCode = status;
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.end(JSON.stringify(data));
}

function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      try {
        const raw = Buffer.concat(chunks).toString('utf8');
        resolve(raw);
      } catch (e) { reject(e); }
    });
    req.on('error', reject);
  });
}

async function handleApiChat(req, res) {
  if (!API_KEY) {
    return sendJson(res, 400, { error: 'Missing DEEPSEEK_API_KEY environment variable' });
  }
  try {
    const raw = await readBody(req);
    const payload = JSON.parse(raw || '{}');
    const message = String(payload.message || '').trim();
    if (!message) return sendJson(res, 400, { error: 'message is required' });

    const postData = JSON.stringify({
      model: 'deepseek-chat',
      messages: [
        { role: 'system', content: '你是一位温柔的居家健康话疗助手，善于安抚、鼓励和提醒用药。请用中文简洁回应，并在需要时给出具体建议。' },
        { role: 'user', content: message }
      ],
      temperature: 0.7,
    });

    const options = {
      hostname: 'api.deepseek.com',
      path: '/v1/chat/completions',
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    };

    const apiReq = https.request(options, (apiRes) => {
      const chunks = [];
      apiRes.on('data', (d) => chunks.push(d));
      apiRes.on('end', () => {
        try {
          const txt = Buffer.concat(chunks).toString('utf8');
          const json = JSON.parse(txt);
          const content = json?.choices?.[0]?.message?.content || '';
          const model = json?.model || 'deepseek';
          const usage = json?.usage || undefined;
          sendJson(res, 200, { reply: content, model, usage });
        } catch (e) {
          sendJson(res, 500, { error: 'Invalid response from DeepSeek' });
        }
      });
    });
    apiReq.on('error', (e) => sendJson(res, 502, { error: 'Upstream error', detail: String(e) }));
    apiReq.write(postData);
    apiReq.end();
  } catch (e) {
    sendJson(res, 400, { error: 'Bad Request', detail: String(e) });
  }
}

async function handleApiStt(req, res) {
  try {
    const raw = await readBody(req);
    const type = (req.headers['content-type'] || '').toLowerCase();
    if (type.includes('application/json')) {
      const payload = JSON.parse(raw || '{}');
      const transcript = payload.mock ? '（语音转写占位：请稍后配置真实 STT 服务）' : '（语音转写占位：收到 JSON 请求）';
      return sendJson(res, 200, { transcript });
    } else {
      const sizeKB = Math.max(1, Math.round(Buffer.byteLength(raw, 'utf8') / 1024));
      const transcript = `（语音转写占位：收到二进制音频 ~${sizeKB}KB）`;
      return sendJson(res, 200, { transcript });
    }
  } catch (e) {
    return sendJson(res, 400, { error: 'Bad Request', detail: String(e) });
  }
}

const server = http.createServer((req, res) => {
  const parsed = url.parse(req.url);
  const method = (req.method || 'GET').toUpperCase();
  let pathname = decodeURIComponent(parsed.pathname || '/');

  // API routes
  if (pathname === '/api/chat' && method === 'POST') {
    return handleApiChat(req, res);
  }
  if (pathname === '/api/stt' && method === 'POST') {
    return handleApiStt(req, res);
  }
  if (pathname === '/api/health' && method === 'GET') {
    return sendJson(res, 200, { ok: true });
  }

  // Static files
  if (pathname === '/') pathname = '/index.html';
  const filePath = safeResolve(pathname);
  fs.stat(filePath, (err, stat) => {
    if (err || !stat.isFile()) {
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
      res.end('Not Found');
      return;
    }
    const ext = path.extname(filePath).toLowerCase();
    res.setHeader('Content-Type', TYPES[ext] || 'application/octet-stream');
    const stream = fs.createReadStream(filePath);
    stream.on('error', () => { res.statusCode = 500; res.end('Server Error'); });
    stream.pipe(res);
  });
});

server.listen(PORT, () => {
  console.log(`Web server + API ready at http://localhost:${PORT}/`);
  if (!API_KEY) console.log('WARN: DEEPSEEK_API_KEY not set, /api/chat will return 400.');
});